package com.wh;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 利用http协议向客户端输出页面。
 * @author wh
 *
 */
public class Processor extends Thread{
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public final static String WEB_ROOT = "D:\\project";
	
	public Processor (Socket socket) {// 处理socket，整理出socket的输入输出流。
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		String filename = pare(in);
		this.sendFile(filename);
	}
	
	private String pare(InputStream in) {// 解析
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;
		try {
			String httpMessage = br.readLine();
			System.out.println(httpMessage);
			String[] content = httpMessage.split(" ");
			if (content.length != 3) {
				this.sendErrorMessage(400, "Client query error!");
				return null;
			}
			filename = content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return filename;
	}
	
	public void sendErrorMessage(int errorCode, String errorMessage) {
		out.println("HTTP/1.0 " + errorCode + " " + errorMessage);
		out.println("content-type:text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message!");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode:" + errorCode + "ErrorMessage:" + errorMessage + "</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	
	public void sendFile(String fileName) {
		File file = new File(Processor.WEB_ROOT + fileName);// 获取文件
		if (!file.exists()) {
			sendErrorMessage(404, "File not found!");
			return;
		}
		
		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int) file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
